var createError = require('http-errors');
var express = require('express')
var path = require('path')
var logger = require('morgan')
const cors = require('cors');       // 添加 CORS 中间件来允许来自前端源的请求，上传文件需要用到这个


var editDynamicsRouter = require('./routes/editDynamics');
var modifyCoverRouter = require('./routes/modifyCover');
var modifyHeadImgRouter = require('./routes/modifyHeadImg');

var app = express()

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs');

app.use(cors());
app.use(logger('dev')); 
app.use(express.json()); 
app.use(express.urlencoded({ extended: false })); 
app.use(express.static(path.join(__dirname, 'public')))
  

// 上传文件所用的路由
app.use('/api/editDynamics', editDynamicsRouter);
app.use('/api/modifyCover', modifyCoverRouter);
app.use('/api/modifyHeadImg', modifyHeadImgRouter);


// 访问了不存在的页面那么这里就会执行，将错误传递給下一个中间件
app.use(function(req, res, next) {
  next(createError(404));
});

// 错误处理
app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
